package cn.ljy.authority.web.controller.frontend;

import cn.ljy.authority.config.security.TokenUtil;
import cn.ljy.authority.config.sms.SmsService;
import cn.ljy.authority.model.SysPhoneVerificationCode;
import cn.ljy.authority.model.common.AuthorityConstant;
import cn.ljy.authority.service.SysPhoneVerificationCodeService;
import cn.ljy.authority.service.SysUserService;
import cn.ljy.authority.service.SysUserTokenFrontendService;
import cn.ljy.authority.web.controller.backstage.BaseController;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.utils.password.VerificationCodeGenerator;
import cn.ljy.common.utils.validator.MobilePhoneValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

@Api(tags = "前台登录模块")
@RestController
@RequestMapping(value = "/frontend")
@Validated
public class FrontendController extends BaseController {

    @Autowired
    private SysUserTokenFrontendService sysUserTokenFrontendService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SysPhoneVerificationCodeService phoneVerificationCodeService;

    //通过阿里云短信功能发送手机验证码到手机
    @ApiOperation(value = "发送手机注册的验证码")
    @GetMapping("/sendTelCodeToReg")
    @Transactional  // 开启事务，当手机短信发送失败时，会回滚事务
    public ResponseData sendTelCodeToReg(@NotBlank(message="请输入手机号码")String tel){
        ResponseData responseData=null;
        //1.验证手机号码格式
        if(!MobilePhoneValidator.isValidMobilePhone(tel)){
            responseData=ResponseData.error("手机号码格式错误");
        } else if(sysUserService.existsByTel(tel)){//判断该手机号是否已经注册
            responseData=ResponseData.error("该手机号已经注册，请选择其他号码注册");
        }else{
            // 1. 生成6位随机验证码
            String code= VerificationCodeGenerator.generateCode(6,1);
            // 2. 将验证码存储到日志中
            SysPhoneVerificationCode phoneVerificationCode=new SysPhoneVerificationCode();
            phoneVerificationCode.setPhone(tel);
            phoneVerificationCode.setCode(code);
            phoneVerificationCode.setIp(super.getClientIp());//ip地址
            phoneVerificationCode.setType(SysPhoneVerificationCode.SysPhoneVerificationCodeType.REG);//验证码类型
            phoneVerificationCodeService.save(phoneVerificationCode);
            //3.发送手机验证码
            try {
                //调用阿里云短信服务发送验证码
                smsService.sendCode(tel,code);
                responseData=ResponseData.success(String.format("验证码%s发送成功",code));
            } catch (Exception e) {
                throw new MyServiceException("验证码发送失败");
            }
        }
        return responseData;
    }


    @ApiOperation(value = "手机账户注册")
    @GetMapping("/regFromTel")
    public ResponseData reg(@NotBlank(message="请输入手机号码")String tel,@NotBlank(message="请输入短信验证码")String code){
        sysUserService.regFromTel(tel,code);
        return ResponseData.success(String.format("手机号注册成功，初始密码为%s","123456"));
    }

    //通过阿里云短信功能发送手机验证码到手机
    @ApiOperation(value = "发送手机登录的验证码")
    @GetMapping("/sendTelCodeToLogin")
    @Transactional  // 开启事务，当手机短信发送失败时，会回滚事务
    public ResponseData sendTelCodeToLogin(@NotBlank(message="请输入手机号码")String tel){
        ResponseData responseData=null;
        //1.验证手机号码格式
        if(!MobilePhoneValidator.isValidMobilePhone(tel)){
            responseData=ResponseData.error("手机号码格式错误");
        } else if(!sysUserService.existsByTel(tel)){//判断该手机号是否已经注册
            responseData=ResponseData.error("该手机号还没有注册，请先注册");
        }else{
            // 2. 生成6位随机验证码
            String code= VerificationCodeGenerator.generateCode(6,1);
            // 3. 将验证码存储到日志中
            SysPhoneVerificationCode phoneVerificationCode=new SysPhoneVerificationCode();
            phoneVerificationCode.setPhone(tel);
            phoneVerificationCode.setCode(code);
            phoneVerificationCode.setIp(super.getClientIp());//ip地址
            phoneVerificationCode.setType(SysPhoneVerificationCode.SysPhoneVerificationCodeType.LOGIN);//验证码类型
            phoneVerificationCodeService.save(phoneVerificationCode);
            //3.发送手机验证码
            try {
                //调用阿里云短信服务发送验证码
                smsService.sendCode(tel,code);
                responseData=ResponseData.success(String.format("验证码%s发送成功",code));
            } catch (Exception e) {
                throw new MyServiceException("验证码发送失败");
            }
        }
        return responseData;
    }

    @ApiOperation(value = "PC端账户登录")
    @GetMapping("/pc/login")
    public ResponseData loginOfPc(String username,String password){
        String token=sysUserTokenFrontendService.loginAndGetToken(username,password, AuthorityConstant.CLIENT_PC);
        if(StringUtils.hasLength(token)){
            return ResponseData.success(token);
        }else{
            return ResponseData.error("登录失败");
        }
    }

    @ApiOperation(value = "移动端账户登录")
    @GetMapping("/mobile/login")
    public ResponseData loginOfmobile(String username,String password){
        String token=sysUserTokenFrontendService.loginAndGetToken(username,password, AuthorityConstant.CLIENT_MOBILE);
        if(StringUtils.hasLength(token)){
            return ResponseData.success(token);
        }else{
            return ResponseData.error("登录失败");
        }
    }

    @ApiOperation(value = "学生注销")
    @GetMapping("/logout")
    public ResponseData logout(){
        //读取token的值
        String token= TokenUtil.getAppToken();
        //移除tokeen
        sysUserTokenFrontendService.removeUserToken(token);
        return ResponseData.success("注销成功");
    }

    @ApiOperation(value = "获取当前登录账户信息")
    @GetMapping("/user/session")
    public ResponseData session(HttpServletRequest request){
        //读取token的值
        String token= TokenUtil.getAppToken();
        return ResponseData.success(sysUserTokenFrontendService.getUserFromToken(token));
    }




}
